package com.example.emos.wx.config.shiro;

import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.example.emos.wx.exception.EmosException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * @Author yctc
 * @Date 2021/3/6 14:24
 * @Version 1.0
 */
@Component
@Slf4j
public class JwtUtil {
    @Value("${emos.jwt.secret}")
    private String secret;

    @Value("${emos.jwt.expire}")
    private int expire;

    /**
     * 生成token
     */
    public String createToken(int userId) {
        // date=偏移后的日期.做日期偏移，(当前日期,日期单位（天）,参数值（偏移几天）)
        Date date = DateUtil.offset(new Date(), DateField.DAY_OF_YEAR, 5);
        //创建加密算法对象
        Algorithm algorithm = Algorithm.HMAC256(secret);
        //创建内部类对象
        JWTCreator.Builder builder = JWT.create();
        //生成 token
        String token = builder.withClaim("userId", userId).withExpiresAt(date).sign(algorithm);
        return token;
    }

    /**
     * 从token中获得userId
     * JWT.decode(token) 解码方法
     */
    public int getUserId(String token) {
        try {
            //对token进行解码
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("userId").asInt();
        } catch (Exception e) {
            throw new EmosException("token无效");
        }
    }

    /**
     * 验证token的有效性
     * 1.验证通过无返回值
     * 2.验证失败抛异常 RuntimeException
     */
    public void verifierToken(String token) {
        //创建算法对象,不能直接new,需要调用工厂方法
        Algorithm algorithm = Algorithm.HMAC256(secret);
        //用算法对象进行解密
        JWTVerifier verifier = JWT.require(algorithm).build();
        verifier.verify(token);
    }
}
